package net.muchine.web.front.handler;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.muchine.web.front.session.UserSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class UserAuthenticationInterceptor implements HandlerInterceptor {
	
	@Autowired private UserSession session;
		
	private String[] publicViews = new String[] {
		 "/"
		,"/public/.*"
		,"/account/login"
	};
	
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView mav) throws Exception {
		if (mav == null) return;
		
		// If redirect to another url, nothing is put to the model.
		if (mav.getViewName().startsWith("redirect:")) return;
		
		mav.addObject("session", session);
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String path = request.getServletPath();
		
		// If a user is not logged in and has requested non-public pages, redirect the user to the login page.
		boolean loginRequired = true;
		for (String publicView : publicViews) {
			if (path.matches(publicView)) loginRequired = false;
		}
		
		if (loginRequired && session.getSeq() == null) {
			response.sendRedirect(
					request.getContextPath() + "/account/login?backUrl=" + 
					URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"));
			return false;
		}
		
		return true;
	}
	
	public static void main(String[] args) {
		String pattern = "/public/.*";
		System.out.println("/public/123123".matches(pattern));
		
		pattern = "/";
		System.out.println("/".matches(pattern));
	}
}
